<?php

require_once "ZendX/JQuery/View/Helper/UiWidget.php";

class Zen_View_Helper_Autocomplete_Widget extends ZendX_JQuery_View_Helper_UiWidget
{
    /**
     * Create a jQuery UI Widget Date Picker
     *
     * @link   http://docs.jquery.com/UI/Datepicker
     * @param  string $id
     * @param  string $value
     * @param  array  $params jQuery Widget Parameters
     * @param  array  $attribs HTML Element Attributes
     * 			multiple - мультиавтоподстановка
     * 			delimiter - разделитель между элементами
     * 			url - источник данных сервера
     * @return string
     */
    public function autocomplete_Widget($id, $value = null, array $params = array(), array $attribs = array())
    {
   	
        $attribs = $this->_prepareAttributes($id, $value, $attribs);

        $jquery = $this->view->jQuery();
        $jquery->enable(); // enable jQuery Core Library
		
        $jquery->addStylesheet('/cms/library/Zen/View/Helper/Autocomplete/css/common.css');
        
        $delimiter = ( isset($attribs['delimiter'])) ? $attribs['delimiter'] : ',';
        
        $js = "	function split( val ) {
					return val.split( /$delimiter\s*/ );
				}
				function extractLast( term ) {
					return split( term ).pop();
				}
		";
        
        if (! isset($params['source'])) return '';
        
        $multiple = ( isset($attribs['multiple'])) ? $attribs['multiple'] : false;

        if ($multiple) {
			$params['search'] = new Zend_Json_Expr("function() { var term = extractLast( this.value ); if ( term.length < 2 ) {return false;}}");
	        $params['focus'] = new Zend_Json_Expr("function() { return false; }");
	        $params['select'] = new Zend_Json_Expr("function( event, ui ) {var terms = split( this.value ); terms.pop(); terms.push( ui.item.value ); terms.push( '' ); this.value = terms.join( '$delimiter ' ); return false; }");
	        
	        $url = $params['source'];
	        $params['source'] = new Zend_Json_Expr("function( request, response ){ $.getJSON( '$url', {term: extractLast( request.term )	}, response );}");
        }
                
        $params = ZendX_JQuery::encodeJson($params);
        
        $js .= sprintf('%s("#%s").autocomplete(%s);',
                ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(),
                $attribs['id'],
                $params
        );

        $this->jquery->addOnLoad($js);

        return $this->view->formText($id, $value, $attribs);
    }

   
}